# -*- coding:utf-8 -*-
# author:jmz

import time
import urllib
import hashlib
import urllib.parse
import urllib.request

# 这里填写你申请到的APPkey
app_key = '26056555'
appSecret = '80010d73b703b59a0af5ecd56415665c'


# 排序
def ksort(d):
    return [(k, d[k]) for k in sorted(d.keys())]


# MD5加密
def md5(s, raw_output=False):
    """Calculates the md5 hash of a given string"""
    res = hashlib.md5(s.encode())
    if raw_output:
        return res.digest()
    return res.hexdigest()


# 计算sign
def createSign(paramArr):
    sign = appSecret
    paramArr = ksort(paramArr)

    for _, v in paramArr:
        if len(v) == 2 and v[0] != '' and v[1] != '':
            sign += v[0] + str(v[0])
    sign += appSecret
    sign = md5(sign).upper()
    return sign


# 参数排序
def createStrParam(paramArr):
    strParam = ''
    for k, v in paramArr.items():
        if k != '' and v != '':
            strParam += k + '=' + urllib.parse.quote_plus(v) + '&'
    return strParam


# 高效API调用示例
def gxapi(postparm={}):
    # 公共参数，一般不需要修改
    paramArr = {'app_key': app_key,
                'v': '2.0',
                'sign_method': 'md5',
                'format': 'json',
                'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
                }

    paramArr = {**paramArr, **postparm}

    sign = createSign(paramArr)
    strParam = createStrParam(paramArr)
    strParam += 'sign=' + sign
    url = 'http://gw.api.tbsandbox.com/router/rest?' + strParam
    res = urllib.request.urlopen(url).read()
    return res


if __name__ == '__main__':
    # 业务参数
    postparm = {
        'method': 'taobao.tbk.item.get',
        'fields': 'num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick',
        'q': "女装",
        'cat': '16,18',
        'itemloc': '杭州',
        'sort': 'tk_rate_des',
        'page_size': '50',
    }
    print(gxapi(postparm))
